<?php
namespace App\Http\Controllers\Safe;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\MLog;
use App\Utils\GDUtil;
use App\Utils\MenuUtil;
use App\Utils\SSUtil;
use Bican\Roles\Models\Permission;
use Bican\Roles\Models\Role;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 管理员相关API控制器
 */
class AdminController extends Controller
{
    /**
     * 管理员登录API
     */
    public function loginAct(Request $request)
    {

        //效验接口数据
        if (!$this->validateReq($request,
            [   //字段合法性效验
                "username" => "required|alpha|between:3,30",
                'userpass' => array('Regex:/^(^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{10,}$)/'),
                'yzmcode'  => 'required|numeric',
            ],
            [   //效验失败提醒
                "username.required" => "请填写用户名！",
                "username.alpha"    => "用户名只能为纯字母！",
                "username.between"  => "用户名只能3-30位之间！",
                "userpass.regex"    => "账号或密码格式错误！",
                "yzmcode.numeric"   => "验证码必须为数字！"
            ])
        ) {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return $this->apiJson();
        }

        //效验验证码
        if (ss(GDUtil::YZM_ADMIN_CODE) != $request->yzmcode) {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "验证码错误！");
            return $this->apiJson();
        }
        if ($admin = Admin::loginValid($request)) { //效验账号密码
            $admin->loginStatus()->refreshIP($request);
            MLog::log("管理员 $admin->username 登录系统！");

            //构造接口返回数据
            $this->data = $this->makeJsCode(0, "登录成功！");
            $this->data['info'] = [];
            $this->data['info']['id'] = $admin->id;
            $this->data['info']['username'] = $admin->username;
            $this->data['info']['title'] = cache("kv_site_name");
            $this->data['info']['menus'] = MenuUtil::adminCanMenus($admin);
        } else {
            $this->refreshYZM();
            $this->data = $this->makeJsCode(1, "账号密码错误！");
        }
        return $this->apiJson();
    }

    /**
     * 退出当前管理员的登陆
     */
    public function exitAct()
    {
        SSUtil::flush();
        return redirect()->route('admin.login-page');
    }

    /**
     * 管理员列表
     */
    public function adminsPage()
    {
        $this->data['admins'] = Admin::where('super', 0)->get();
        return view("admin.admins")->with($this->data);
    }

    /**
     * 管理员信息编辑界面
     */
    public function adminsEditPage(Request $request, $id = 0)
    {
        $this->data['roles'] = Role::all();
        $this->data['admin'] = Admin::find($id);
        return view('admin.admin_edit')->with($this->data);
    }

    /**
     * 管理员信息保存
     */
    public function adminsSave(Request $request, $id = 0)
    {
        if (!$this->validateReq($request, Admin::saveRulesWithMsg(0), Admin::saveRulesWithMsg(1))) {
            $this->data = $this->makeJsCode(1, $this->errors->first());
            return response()->json($this->data);
        }

        //新添加管理员需检查管理员是否重名
        $admin = Admin::find($id);
        if (empty($admin)) {
            $admin = new Admin();
            if ($admin->existUserName($request->username)) {
                $this->data = $this->makeJsCode(1, "用户名已经存在！");
                return response()->json($this->data);
            }
        }

        try {
            DB::transaction(function () use ($request, $admin) {
                if ($admin->createOrSave($request)) {
                    $admin->detachAllRoles();
                    $roles = Role::find($request->roles);
                    $admin->attachRole($roles);
                    $this->data = $this->makeJsCode(0, "保存管理员成功！");
                    MLog::log("修改了管理员 $admin->username 的数据，修改后角色为 $roles->name !");
                } else {
                    $this->data = $this->makeJsCode(1, "保存管理员失败！");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "保存管理员失败！");
        }
        return response()->json($this->data);
    }

    /**
     * 删除管理员
     */
    public function adminDel($id = 0)
    {
        $admin = Admin::find($id);
        if (!empty($admin)) {
            $admin->detachAllRoles();   //先脱掉所有身份
            $admin->delete();
            $this->data = $this->makeJsCode(0, "删除成功！");
            MLog::log("删除了管理员 $admin->username !");
        } else {
            $this->data = $this->makeJsCode(1, "要删除的管理员不存在！");
        }
        return back()->with($this->data);
    }


    /**
     * 角色列表
     */
    public function rolesPage()
    {
        $this->data['roles'] = Role::all();
        return view('admin.roles')->with($this->data);
    }

    /**
     * 角色编辑页面
     */
    public function rolesEditPage($id = 0)
    {
        $this->data['roles'] = Role::find($id);
        return view('admin.roles_edit')->with($this->data);
    }

    /**
     * 角色权限存储
     */
    public function rolesSave(Request $request, $id = 0)
    {
        if (!$request->has(['name', 'permissions'])) {
            $this->data = $this->makeJsCode(1, "请填写完整的角色数据！");
            return response()->json($this->data);
        }

        if ($id == 0) { //添加角色判断角色是否存在
            if (Admin::existRoles($request)) {
                $this->data = $this->makeJscode(1, '该角色已存在');
                return response()->json($this->data);
            }
        }

        try {
            DB::transaction(function () use ($request, $id) {
                $role = Role::find($id);
                if (empty($role)) {
                    $role = Role::create([
                        'name'  => $request->name,
                        'slug'  => str_random(16),
                        'level' => 1
                    ]);
                }
                $role->detachAllPermissions();  //创建可用权限(先清空此用户的所有权限)
                foreach ($request->permissions as $check) {
                    $permission = Permission::where('name', $check)->first();
                    if (empty($permission)) {
                        $permission = Permission::create([
                            'name' => $check,
                            'slug' => $check,
                        ]);
                    }
                    $role->attachPermission($permission);
                }
                $this->data = $this->makeJsCode(0, "存储角色成功！");
                MLog::log("修改了角色 $role->name 的权限信息！");
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "存储角色失败！");
        }

        return response()->json($this->data);
    }

    /**
     * 删除角色
     */
    public function rolesDel($id = 0)
    {
        $roles = Role::find($id);
        if (!empty($roles)) {
            try {
                //检查当前角色下面是否还有管理员
                $admins = Admin::all();
                foreach ($admins as $admin) {
                    if ($admin->hasRole($roles->id)) {
                        return back()->with($this->makeJsCode(1, "此角色下还有管理员，不可以删除！"));
                    }
                }
                $roles->detachAllPermissions();//先移除所有的角色权限
                $roles->delete();
                $this->data = $this->makeJsCode(0, "角色删除成功！");
                MLog::log("删除了角色 $roles->name ！");
            } catch (Exception $e) {
                throw  $e;
                $this->data = $this->makeJsCode(1, "角色删除失败！");
            }
        } else {
            $this->data = $this->makeJsCode(1, "要删除的角色不存在！");
        }
        return back()->with($this->data);
    }
}